<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>JavaScript异步编程和Promise | Closure233</title><meta name="author" content="Closure233"><meta name="copyright" content="Closure233"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="JavaScript异步编程和PromiseJavaScript异步编程异步的概念异步（Asynchronous，async）是相对于同步（Synchronous，sync）的一个概念。在传统单线程编程中，程序的运行是同步的（指程序在一个控制流序列中顺序执行）。异步的概念则是不保证执行顺序与原有的序列有顺序关系。简而言之，同步是按代码顺序执行，异步不按代码顺序执行，异步的执行效率更高。  异步就是">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript异步编程和Promise">
<meta property="og:url" content="https://closure.gitee.io/2023/08/04/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E5%92%8CPromise/index.html">
<meta property="og:site_name" content="Closure233">
<meta property="og:description" content="JavaScript异步编程和PromiseJavaScript异步编程异步的概念异步（Asynchronous，async）是相对于同步（Synchronous，sync）的一个概念。在传统单线程编程中，程序的运行是同步的（指程序在一个控制流序列中顺序执行）。异步的概念则是不保证执行顺序与原有的序列有顺序关系。简而言之，同步是按代码顺序执行，异步不按代码顺序执行，异步的执行效率更高。  异步就是">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://closure.gitee.io/images/avatar.gif">
<meta property="article:published_time" content="2023-08-03T16:12:00.000Z">
<meta property="article:modified_time" content="2023-08-08T05:13:59.438Z">
<meta property="article:author" content="Closure233">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://closure.gitee.io/images/avatar.gif"><link rel="shortcut icon" href="/images/moss.ico"><link rel="canonical" href="https://closure.gitee.io/2023/08/04/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E5%92%8CPromise/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: true,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JavaScript异步编程和Promise',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-08-08 13:13:59'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/images/avatar.gif" onerror="onerror=null;src='/images/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">11</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">0</div></a></div><hr/></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background: url(/images/cover/cover1.jpg)"><nav id="nav"><span id="blog-info"><a href="/" title="Closure233"><span class="site-name">Closure233</span></a></span><div id="menus"><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">JavaScript异步编程和Promise</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2023-08-03T16:12:00.000Z" title="Created 2023-08-04 00:12:00">2023-08-04</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2023-08-08T05:13:59.438Z" title="Updated 2023-08-08 13:13:59">2023-08-08</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JavaScript异步编程和Promise"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="JavaScript异步编程和Promise"><a href="#JavaScript异步编程和Promise" class="headerlink" title="JavaScript异步编程和Promise"></a>JavaScript异步编程和Promise</h1><h2 id="JavaScript异步编程"><a href="#JavaScript异步编程" class="headerlink" title="JavaScript异步编程"></a>JavaScript异步编程</h2><h3 id="异步的概念"><a href="#异步的概念" class="headerlink" title="异步的概念"></a>异步的概念</h3><p>异步（Asynchronous，async）是相对于同步（Synchronous，sync）的一个概念。在传统单线程编程中，程序的运行是同步的（指程序在一个控制流序列中顺序执行）。异步的概念则是不保证执行顺序与原有的序列有顺序关系。简而言之，同步是按代码顺序执行，异步不按代码顺序执行，异步的执行效率更高。</p>
<p><img src="C:\Users\Rong\AppData\Roaming\Typora\typora-user-images\image-20230806174044785.png" alt="image-20230806174044785"></p>
<p>异步就是从主线程发射一个子线程来完成任务。</p>
<h3 id="异步编程的使用场景"><a href="#异步编程的使用场景" class="headerlink" title="异步编程的使用场景"></a>异步编程的使用场景</h3><p>在前端编程中，可以在主线程处理一些简短快速的操作，主线程作为一个线程，不能同时接收多方面的请求，所以，当一个事件没有结束时，界面无法处理其他请求（线程阻塞）。为了避免阻塞，可以使用子线程来完成一些比较消耗计算资源和时间的事件，如读取大文件或发出网络请求。因为子线程独立于主线程，所以即使出现阻塞也不会影响主线程的运行。</p>
<p>子线程有一个局限性：主进程发出子线程完成后无法监控子线程的状态。为了解决这个问题，需要在异步操作中通过<strong>回调函数</strong>实现异步任务的结果处理。</p>
<h3 id="回调函数"><a href="#回调函数" class="headerlink" title="回调函数"></a>回调函数</h3><p>回调函数是异步任务启动时设置的一个函数，用于在任务结束后处理任务结果的函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">callback</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;response&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">setTimeout</span>(callback, <span class="number">5000</span>);</span><br></pre></td></tr></table></figure>

<p>上述代码中的<strong>setTimeout函数</strong>的第一个参数是一个回调函数，第二参数是等待时间。这个函数执行后产生一个子线程，在等待时间后，执行回调函数<code>callback</code>输出结果。</p>
<h2 id="Promise"><a href="#Promise" class="headerlink" title="Promise"></a>Promise</h2><p>Promise是一个ECMAScript 6（ES6）提供的类，用于优雅的处理复杂的异步任务。Promise将异步任务中的执行代码和结果处理清晰的分离开来，</p>
<h3 id="构造Promise对象"><a href="#构造Promise对象" class="headerlink" title="构造Promise对象"></a>构造Promise对象</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">	<span class="comment">// something to do</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>在实际应用中，我们需要实现复杂的多次异步任务：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 分多次输出字符串，第一次间隔1秒，第二次间隔2秒，第三次间隔三秒</span></span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;First&quot;</span>);</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;Second&quot;</span>);</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;Third&quot;</span>);</span><br><span class="line">        &#125;, <span class="number">3000</span>);</span><br><span class="line">    &#125;, <span class="number">2000</span>);</span><br><span class="line">&#125;, <span class="number">1000</span>);</span><br></pre></td></tr></table></figure>

<p>上述代码使用了<strong>“函数瀑布”</strong>的方式实现多次异步任务。但是，这样的实现方式显而易见的繁琐和冗余。采用<strong>Promise</strong>实现：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span>(<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;First&quot;</span>);</span><br><span class="line">        <span class="title function_">resolve</span>();</span><br><span class="line">    &#125;, <span class="number">1000</span>)</span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;Second&quot;</span>);</span><br><span class="line">            <span class="title function_">resolve</span>();</span><br><span class="line">        &#125;, <span class="number">2000</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;Third&quot;</span>);</span><br><span class="line">    &#125;, <span class="number">3000</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>Promise将”函数瀑布“中的嵌套结构变成了顺序结构，显然更易理解和编写。</p>
<h3 id="Promise的构造函数"><a href="#Promise的构造函数" class="headerlink" title="Promise的构造函数"></a>Promise的构造函数</h3><p>Promise构造函数是<strong>JavaScript</strong>中用于创建<strong>Promise</strong>对象的内置构造函数。Promise 构造函数接受一个函数（起始函数）作为参数，这个函数是<strong>同步的</strong>并且会<strong>立即执行</strong>，包含两个参数 <code>resolve</code>和<code>reject</code>，分别表示Promise成功和失败的状态。</p>
<p>起始函数执行成功时，调用resolve函数并传递成功的结果；当起始函数执行失败时，调用reject函数并传递失败的原因。</p>
<p>Promise构造函数会返回一个<strong>Promise对象</strong>，该对象具有以下几种方法：</p>
<ul>
<li>then：用于处理 Promise 成功状态的回调函数；</li>
<li>catch：用于处理 Promise 失败状态的回调函数（捕捉错误）；</li>
<li>finally：无论 Promise 成功还是失败，都会执行的回调函数。</li>
</ul>
<p>构造Promise对象时，起始函数会被同步执行。使用实例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> promise = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 异步任务</span></span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(<span class="title class_">Math</span>.<span class="title function_">random</span>() &lt; <span class="number">0.5</span>) &#123;</span><br><span class="line">            <span class="title function_">resolve</span>(<span class="string">&#x27;success&#x27;</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="title function_">reject</span>(<span class="string">&#x27;error&#x27;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, <span class="number">1000</span>)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">promise.<span class="title function_">then</span>(<span class="function"><span class="params">result</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(result);</span><br><span class="line">&#125;).<span class="title function_">catch</span>(<span class="function"><span class="params">error</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(error);</span><br><span class="line">&#125;).<span class="title function_">finally</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;end&#x27;</span>)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><code>then()</code>、<code>catch()</code>、<code>finally()</code>这三个Promise的方法的参数都是一个函数，<code>then()</code>可以将参数中的函数添加到当前Promise的<strong>正常执行</strong>序列，<code>catch()</code>则是设置Promise的异常处理序列，<code>finally()</code> 是在 Promise 执行的最后一定会执行的序列。 <code>then()</code>传入的函数会按顺序依次执行，有任何异常都会直接跳到 <code>catch()</code>序列：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> res = <span class="number">0</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        <span class="title function_">resolve</span>(++res);</span><br><span class="line">    &#125;, <span class="number">1000</span>);</span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">    <span class="keyword">return</span> ++res; <span class="comment">// 传递到下一个then</span></span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">&#125;).<span class="title function_">catch</span>(<span class="function">(<span class="params">error</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(error);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>执行结果：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">0</span></span><br><span class="line"><span class="number">1</span></span><br><span class="line"><span class="number">2</span></span><br></pre></td></tr></table></figure>

<p><code>resolve()</code>中可以放置一个参数用于向下一个<code>then()</code>传递一个值，<code>then()</code>中的函数也可以返回一个值传递给<code>then()</code>。但是，如果 then 中返回的是一个<strong>Promise对象</strong>，那么下一个 then 将相当于对这个返回的 Promise 进行操作。</p>
<p><code>reject()</code>的参数中一般会传递一个异常（error）给之后的 catch 函数用于处理异常。</p>
<p>注意以下两点：</p>
<ul>
<li>resolve 和 reject 的作用域只有<strong>起始函数</strong>，不包括 then 以及其他序列；</li>
<li>resolve 和 reject 并不能够使起始函数停止运行，需要使用<code>return</code>终止起始函数。</li>
</ul>
<h3 id="Promise函数"><a href="#Promise函数" class="headerlink" title="Promise函数"></a>Promise函数</h3><p>上述的用于简化“函数瀑布”的“计时器”程序可以使用更加简单的Promise函数方法实现，将核心部分写成一个Promise函数：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 核心功能</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">print</span>(<span class="params">delay, message</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(message);</span><br><span class="line">            <span class="title function_">resolve</span>();</span><br><span class="line">        &#125;, delay);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 功能实现</span></span><br><span class="line"><span class="title function_">print</span>(<span class="number">1000</span>, <span class="string">&quot;First&quot;</span>).<span class="title function_">then</span>(<span class="function">() =&gt;</span> </span><br><span class="line">	<span class="title function_">print</span>(<span class="number">2000</span>, <span class="string">&quot;Second&quot;</span>);</span><br><span class="line">).<span class="title function_">then</span>(<span class="function">() =&gt;</span></span><br><span class="line">    <span class="title function_">print</span>(<span class="number">3000</span>, <span class="string">&quot;Third&quot;</span>)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

<p>这种返回一个Promise对象的函数称为Promise函数，Promise函数常用于开发异步操作的库。</p>
<h3 id="异步函数（async-function）"><a href="#异步函数（async-function）" class="headerlink" title="异步函数（async function）"></a>异步函数（async function）</h3><p>在上述Promise函数的介绍中，我们使用Promise函数实现了使用不同的时间间隔输出三行文本，我们可以通过使用异步函数的写法对上述代码进行简化：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">asyncFunc</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">print</span>(<span class="number">1000</span>, <span class="string">&quot;First&quot;</span>);</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">print</span>(<span class="number">2000</span>, <span class="string">&quot;Second&quot;</span>);</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">print</span>(<span class="number">3000</span>, <span class="string">&quot;Third&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">asyncFunc</span>();</span><br></pre></td></tr></table></figure>

<p>显而易见的是，异步代码的风格转化为了同步代码的写法，这样更易于开发者理解和维护代码。我们使用一个<code>async</code>关键字定义一个异步函数。异步函数（async function）中可以使用<code>await</code>关键字，<code>await</code>指令后必须紧接着一个Promise，异步函数会在这个Promise运行中暂停，直至其结束再继续运行之后的代码。</p>
<p>异步函数的原理与Promise原生API的机制是一致的，它是ES2017 标准增加的一个语法糖，它提供了一种更直观和同步化的方式来编写异步代码。通过使用 async 关键字声明一个函数为异步函数，并使用 await 关键字来等待 Promise 对象的解决（即完成或拒绝），我们可以以同步的方式编写异步操作的代码。</p>
<p>异步函数的异常处理（使用try-catch块）：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">asyncFunc</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> res = <span class="keyword">await</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 成功</span></span><br><span class="line">            <span class="keyword">if</span> (success) &#123;</span><br><span class="line">                <span class="title function_">resolve</span>(<span class="string">&quot;Return value&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 失败</span></span><br><span class="line">            <span class="keyword">if</span> (error) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="string">&quot;error!&quot;</span>; <span class="comment">// or reject(&quot;error!&quot;)</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res); <span class="comment">// 获取正常的返回值&quot;Return value&quot;</span></span><br><span class="line">    &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(error);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">asyncFunc</span>();</span><br></pre></td></tr></table></figure>



















</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a target="_blank" rel="noopener" href="https://gitee.com/closure233">Closure233</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="https://closure.gitee.io/2023/08/04/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E5%92%8CPromise/">https://closure.gitee.io/2023/08/04/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E5%92%8CPromise/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/js/">js</a></div><div class="post_share"><div class="social-share" data-image="/images/avatar.gif" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/08/04/Ajax%E8%AF%B7%E6%B1%82/" title="AJAX请求"><div class="cover" style="background: url(/images/cover/cover1.jpg)"></div><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">AJAX请求</div></div></a></div><div class="next-post pull-right"><a href="/2023/07/14/JavaScript%E6%95%B0%E7%BB%84%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95/" title="JavaScript数组常用方法"><div class="cover" style="background: url(/images/cover/cover1.jpg)"></div><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">JavaScript数组常用方法</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2023/05/10/JavaScript%E7%9A%84%E5%86%92%E6%B3%A1%E5%92%8C%E6%8D%95%E8%8E%B7/" title="JavaScript的冒泡和捕获"><div class="cover" style="background: url(/images/cover/cover1.jpg)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-10</div><div class="title">JavaScript的冒泡和捕获</div></div></a></div><div><a href="/2023/05/08/JavaScript%E7%9A%84%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%92%8C%E9%9A%90%E5%BC%8F%E8%BD%AC%E6%8D%A2/" title="JavaScript的数据类型和隐式转换"><div class="cover" style="background: url(/images/cover/cover1.jpg)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-08</div><div class="title">JavaScript的数据类型和隐式转换</div></div></a></div><div><a href="/2023/05/20/JavaScript%E7%9A%84%E5%8E%9F%E5%9E%8B%E5%92%8C%E5%8E%9F%E5%9E%8B%E9%93%BE/" title="JavaScript的原型和原型链"><div class="cover" style="background: url(/images/cover/cover1.jpg)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-20</div><div class="title">JavaScript的原型和原型链</div></div></a></div><div><a href="/2023/07/14/JavaScript%E6%95%B0%E7%BB%84%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95/" title="JavaScript数组常用方法"><div class="cover" style="background: url(/images/cover/cover1.jpg)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-07-14</div><div class="title">JavaScript数组常用方法</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/images/avatar.gif" onerror="this.onerror=null;this.src='/images/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Closure233</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">11</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/catfish233"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E5%92%8CPromise"><span class="toc-number">1.</span> <span class="toc-text">JavaScript异步编程和Promise</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B"><span class="toc-number">1.1.</span> <span class="toc-text">JavaScript异步编程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E7%9A%84%E6%A6%82%E5%BF%B5"><span class="toc-number">1.1.1.</span> <span class="toc-text">异步的概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E7%9A%84%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-number">1.1.2.</span> <span class="toc-text">异步编程的使用场景</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0"><span class="toc-number">1.1.3.</span> <span class="toc-text">回调函数</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise"><span class="toc-number">1.2.</span> <span class="toc-text">Promise</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9E%84%E9%80%A0Promise%E5%AF%B9%E8%B1%A1"><span class="toc-number">1.2.1.</span> <span class="toc-text">构造Promise对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise%E7%9A%84%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="toc-number">1.2.2.</span> <span class="toc-text">Promise的构造函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise%E5%87%BD%E6%95%B0"><span class="toc-number">1.2.3.</span> <span class="toc-text">Promise函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E5%87%BD%E6%95%B0%EF%BC%88async-function%EF%BC%89"><span class="toc-number">1.2.4.</span> <span class="toc-text">异步函数（async function）</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/08/08/Axios/" title="Axios"><div style="background: url(/images/cover/cover1.jpg)"></div></a><div class="content"><a class="title" href="/2023/08/08/Axios/" title="Axios">Axios</a><time datetime="2023-08-08T03:30:00.000Z" title="Created 2023-08-08 11:30:00">2023-08-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/08/04/Ajax%E8%AF%B7%E6%B1%82/" title="AJAX请求"><div style="background: url(/images/cover/cover1.jpg)"></div></a><div class="content"><a class="title" href="/2023/08/04/Ajax%E8%AF%B7%E6%B1%82/" title="AJAX请求">AJAX请求</a><time datetime="2023-08-03T16:12:00.000Z" title="Created 2023-08-04 00:12:00">2023-08-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/08/04/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E5%92%8CPromise/" title="JavaScript异步编程和Promise"><div style="background: url(/images/cover/cover1.jpg)"></div></a><div class="content"><a class="title" href="/2023/08/04/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E5%92%8CPromise/" title="JavaScript异步编程和Promise">JavaScript异步编程和Promise</a><time datetime="2023-08-03T16:12:00.000Z" title="Created 2023-08-04 00:12:00">2023-08-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/07/14/JavaScript%E6%95%B0%E7%BB%84%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95/" title="JavaScript数组常用方法"><div style="background: url(/images/cover/cover1.jpg)"></div></a><div class="content"><a class="title" href="/2023/07/14/JavaScript%E6%95%B0%E7%BB%84%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95/" title="JavaScript数组常用方法">JavaScript数组常用方法</a><time datetime="2023-07-14T07:45:00.000Z" title="Created 2023-07-14 15:45:00">2023-07-14</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/06/21/%E7%AE%80%E5%8D%95%E7%9A%84CSS%E6%95%88%E6%9E%9C%E5%AE%9E%E7%8E%B0/" title="简单的CSS效果实现"><div style="background: url(/images/cover/cover1.jpg)"></div></a><div class="content"><a class="title" href="/2023/06/21/%E7%AE%80%E5%8D%95%E7%9A%84CSS%E6%95%88%E6%9E%9C%E5%AE%9E%E7%8E%B0/" title="简单的CSS效果实现">简单的CSS效果实现</a><time datetime="2023-06-21T05:30:00.000Z" title="Created 2023-06-21 13:30:00">2023-06-21</time></div></div></div></div></div></div></main><footer id="footer" style="background: url(/images/cover/cover1.jpg)"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Closure233</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>